<template>
  <div class="app">
    <form-create ref="fc" v-model="fApi" :rule="rule" :option="option" />
    <el-row :gutter="20">
      <el-col :span="6"><el-button @click="channel()">取消</el-button></el-col>
      <el-col :span="6"><el-button type="primary" @click="submitClick()">确定</el-button></el-col>
    </el-row>
  </div>
</template>

<script>
import { add, fetchOptions, queryMenu, createArticle, fetchTree } from '@/api/article'
export default {
  name: 'Form',
  data() {
    return {
      menuId: 71, // 菜单ID 必传
      viewId: 21, // 接口ID 必传
      treeJson: [],
      typeMap: {
        'type-1': 'input',
        'type-2': 'select',
        'type-3': 'radio',
        'type-4': 'checkbox',
        'type-7': 'select',
        'type-9': 'DatePicker',
        'type-10': 'DatePicker',
        'type-11': 'input',
        'type-13': 'hidden',
        'type-14': 'input',
        'type-15': 'switch',
        'type-17': 'tree',
        'type-19': 'tree'
      },
      treeDataMap: {},
      ruleObj: {
        type: '',
        title: '',
        field: '', // 字段名
        value: '', // v-model的value值
        props: {}, // 设置
        options: [], // 下拉
        validate: [] // 检验
      },
      fApi: {}, //
      rule: [], // 字段显示
      option: {
        form: {
          labelWidth: '250px',
          inline: false
        },
        onSubmit: {},
        submitBtn: {
          show: false
        }
      }
    }
  },
  mounted() {
    this.init()
    // 路由获取参数 menuId
    this.menuId = this.$route.query.menuId
    // 路由获取参数 viewId
    this.viewId = this.$route.query.viewId
    // 获取保存接口url
    this.queryMenuClick()
  },
  methods: {
    handleData(resArray) {
      const _this = this
      const array = []
      resArray.forEach(item => {
        // 对象深拷贝
        const ruleObjs = Object.assign({}, _this.ruleObj)
        // 校验列表
        let validateArray = []
        // 公共赋值
        ruleObjs.type = _this.typeMap['type-' + item.editTypeId]
        ruleObjs.title = item.showName
        ruleObjs.field = item.discernName
        ruleObjs.value = item.defaultValue
        console.info(item)
        // 文本
        if (item.editTypeId === 1) {
          const props = {}
          props.disabled = item.isReadonly !== 0
          ruleObjs.props = props
          const validate = {}
          validate.required = item.isRequired !== 0
          validate.type = 'string'
          validate.message = '必填'
          validateArray.push(validate)
          validateArray = this.validatorMethod(validateArray, item.validateRule)
          ruleObjs.validate = validateArray
        }
        // 下拉框
        if (item.editTypeId === 2) {
          ruleObjs.options = this.treeDataMap[item.discernName]
          const props = {}
          props.disabled = item.isReadonly !== 0
          ruleObjs.props = props
          if (item.isRequired !== 0) {
            const validateRule = {}
            validateRule.validator = function(rule, val, d) {
              !val ? d(true) : d()
            }
            validateRule.message = '必选'
            validateArray.push(validateRule)
            ruleObjs.validate = validateArray
          }
        }
        // 单选
        if (item.editTypeId === 3) {
          ruleObjs.options = this.treeDataMap[item.discernName]
          const props = {}
          props.disabled = item.isReadonly !== 0
          ruleObjs.props = props
          if (item.isRequired !== 0) {
            const validateRule = {}
            validateRule.validator = function(rule, val, d) {
              !val ? d(true) : d()
            }
            validateRule.message = '必选'
            validateArray.push(validateRule)
            ruleObjs.validate = validateArray
          }
        }
        // 多选框
        if (item.editTypeId === 4) {
          ruleObjs.options = this.treeDataMap[item.discernName]
          const props = {}
          props.disabled = item.isReadonly !== 0
          ruleObjs.props = props
          const validate = {}
          validate.required = item.isRequired !== 0
          validate.type = 'array'
          validate.message = '必选'
          validateArray.push(validate)
          ruleObjs.validate = validateArray
        }
        // 下拉框(带搜索)
        if (item.editTypeId === 7) {
          ruleObjs.type = 'select'
          ruleObjs.options = this.treeDataMap[item.discernName]
          const props = {}
          props.filterable = true // 是否可搜索
          props.disabled = item.isReadonly !== 0
          ruleObjs.props = props
          if (item.isRequired !== 0) {
            const validateRule = {}
            validateRule.validator = function(rule, val, d) {
              !val ? d(true) : d()
            }
            validateRule.message = '必选'
            validateArray.push(validateRule)
            ruleObjs.validate = validateArray
          }
        }
        // 日期时间（当前时间，只读）
        if (item.editTypeId === 9) {
          ruleObjs.type = 'DatePicker'
          const props = {}
          props.type = 'datetime'
          props.format = 'yyyy-MM-dd HH:mm:ss'
          props.placeholder = '请选择活动日期'
          props.disabled = item.isReadonly !== 0
          ruleObjs.props = props
          const validate = {}
          validate.required = item.isRequired !== 0
          validate.type = 'date'
          validate.message = '请选择时间'
          validateArray.push(validate)
          ruleObjs.validate = validateArray
        }
        // 日期时间
        if (item.editTypeId === 10) {
          ruleObjs.type = 'DatePicker'
          const props = {}
          props.type = 'datetime'
          props.format = 'yyyy-MM-dd HH:mm:ss'
          props.placeholder = '请选择活动日期'
          props.disabled = item.isReadonly !== 0
          ruleObjs.props = props
          const validate = {}
          validate.required = false
          validate.type = 'date'
          validate.message = '请选择时间'
          validateArray.push(validate)
          ruleObjs.validate = validateArray
        }
        // 文本区
        if (item.editTypeId === 11) {
          ruleObjs.type = 'input'
          const props = {}
          props.type = 'textarea'
          props.disabled = item.isReadonly !== 0
          ruleObjs.props = props
          const validate = {}
          validate.required = item.isRequired !== 0
          validate.type = 'string'
          validate.message = '请输入内容'
          validateArray.push(validate)
          validateArray = this.validatorMethod(validateArray, item.validateRule)
          ruleObjs.validate = validateArray
        }
        // 隐藏
        if (item.editTypeId === 13) {
          ruleObjs.type = 'input'
        }
        // 密码
        if (item.editTypeId === 14) {
          const props = {}
          props.type = 'password'
          props.disabled = item.isReadonly !== 0
          ruleObjs.props = props
          const validate = {}
          validate.required = item.isRequired !== 0
          validate.type = 'string'
          validate.message = '请输入密码'
          validateArray.push(validate)
          validateArray = this.validatorMethod(validateArray, item.validateRule)
          ruleObjs.validate = validateArray
        }
        // 开关
        if (item.editTypeId === 15) {
          ruleObjs.type = 'switch'
          const props = {}
          props.disabled = item.isReadonly !== 0
          props.activeValue = '1'
          props.inactiveValue = '0'
          ruleObjs.props = props
        }
        // 下拉树
        if (item.editTypeId === 17) {
          ruleObjs.type = 'tree'
          const props = {}
          props.disabled = item.isReadonly !== 0
          props.data = this.treeDataMap[item.discernName]
          const propss = {}
          propss.label = 'title'
          props.props = propss
          ruleObjs.props = props
        }
        // 下拉树
        if (item.editTypeId === 19) {
          ruleObjs.type = 'tree'
          const validate = {}
          validate.required = item.isRequired !== 0
          validate.type = 'array'
          validate.message = '必选'
          validateArray.push(validate)
          ruleObjs.validate = validateArray
          const props = {}
          props['show-checkbox'] = true
          props.disabled = item.isReadonly !== 0
          props.data = this.treeDataMap[item.discernName]
          const propss = {}
          propss.label = 'title'
          props.props = propss
          ruleObjs.props = props
        }
        array.push(ruleObjs)
      })
      console.info(JSON.stringify(array))
      this.rule = array
    },
    // 保存
    queryMenuClick() {
      const _this = this
      queryMenu({ 'viewid': this.viewid }).then(response => {
        _this.menuUrl = response.data.SysRuleMenu.menuUrl // 拿到左边菜单的id
      })
    },
    // 取消按钮
    channel() {
      this.$router.go(-1)
    },
    // 提交
    submitClick() {
      const $f = this.fApi
      $f.submit((formData, api) => {
        // 提交表单
        this.submit(formData)
      }, (api) => {
        console.info('验证不通过')
        // 验证未通过
      })
    },
    init() {
      // 调用接口
      const _this = this
      add({ menuId: this.menuId }).then(response => {
        const resArray = response.data
        const interfaceArray = []
        resArray.forEach(item => {
          if (item.editTypeId === 17 || item.editTypeId === 19) {
            const interfaceName = new Promise(function(resolve, reject) {
              fetchTree({ groupNo: item.groupId }).then(response => {
                const array = response.data
                _this.treeDataMap[item.discernName] = array
                console.info(array)
                resolve(array)
              })
            })
            interfaceArray.push(interfaceName)
          } else {
            const interfaceName = new Promise(function(resolve, reject) {
              fetchOptions({ groupNo: item.groupId }).then(response => {
                const arrayOptions = []
                const resArrayOptions = response.data
                resArrayOptions.forEach(itemOption => {
                  const option = {}
                  option.value = itemOption.value
                  option.label = itemOption.name
                  arrayOptions.push(option)
                })
                _this.treeDataMap[item.discernName] = arrayOptions
                console.info(arrayOptions)
                resolve(arrayOptions)
              })
            })
            interfaceArray.push(interfaceName)
          }
        })
        Promise.all(interfaceArray).then(res => {
          console.info(res)
          this.handleData(resArray)
        })
      })
    },
    submit(formData) {
      createArticle(formData, this.menuUrl + '/SAVE').then((res) => {
        if (res.result === 1) {
          this.$message.success('添加成功')
          // this.$router.replace({path:'/jurisdiction/administrator'})
        } else {
          this.$message.error('添加失败')
        }
      })
    },
    validatorMethod(validateArray, validateRules) {
      if (!validateRules) {
        return validateArray
      }
      const rules = validateRules.split('|')
      rules.forEach(rule => {
        console.info(rule)
        const ruleMap = rule.split(':')
        const validateRule = {}
        if (ruleMap[0] === 'max') {
          validateRule.type = 'string'
          validateRule.max = parseInt(ruleMap[1])
          console.info(ruleMap[1])
          validateRule.message = '最多' + ruleMap[1] + '个字'
        }
        if (ruleMap[0] === 'min') {
          validateRule.type = 'string'
          validateRule.min = parseInt(ruleMap[1])
          console.info(ruleMap[1])
          validateRule.message = '最少' + ruleMap[1] + '个字'
        }
        if (ruleMap[0] === 'validator') {
          if (ruleMap[1] === '00') {
            validateRule.validator = function(rule, val, d) {
              val && !/^[\u4E00-\u9FA5A-Za-z0-9]+$/.test(val) ? d(true) : d()
            }
            validateRule.message = '只能输入汉字、数字、字母，不可输入非法特殊字符'
          }
          if (ruleMap[1] === '01') {
            validateRule.validator = function(rule, val, d) {
              val && !/^[\u4E00-\u9FA5A-Za-z0-9_]+$/.test(val) ? d(true) : d()
            }
            validateRule.message = '只能输入汉字、数字、字母、下划线'
          }
          if (ruleMap[1] === '02') {
            validateRule.validator = function(rule, val, d) {
              val && !/^[\u4E00-\u9FA5A-Za-z]+$/.test(val) ? d(true) : d()
            }
            validateRule.message = '只能输入汉字、字母，不可输入非法特殊字符'
          }
          if (ruleMap[1] === '03') {
            validateRule.validator = function(rule, val, d) {
              val && !/^[\u4E00-\u9FA5A-Za-z_]+$/.test(val) ? d(true) : d()
            }
            validateRule.message = '只能输入汉字、字母、下划线，不可输入非法特殊字符'
          }
          if (ruleMap[1] === '04') {
            validateRule.validator = function(rule, val, d) {
              val && !/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(val) ? d(true) : d()
            }
            validateRule.message = '请输入正确的邮箱'
          }
          if (ruleMap[1] === '05') {
            validateRule.validator = function(rule, val, d) {
              val && !/^[0-9]*$/.test(val) ? d(true) : d()
            }
            validateRule.message = '只能输入数字'
          }
          if (ruleMap[1] === '06') {
            validateRule.validator = function(rule, val, d) {
              val && !/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/.test(val) ? d(true) : d()
            }
            validateRule.message = '手机号码输入有误，请重新输入'
          }
          if (ruleMap[1] === '07') {
            validateRule.validator = function(rule, val, d) {
              val && !/^\d{15}|\d{18}$/.test(val) ? d(true) : d()
            }
            validateRule.message = '身份证号输入有误，请重新输入'
          }
          if (ruleMap[1] === '08') {
            validateRule.validator = function(rule, val, d) {
              val && !/^[\u4E00-\u9FA5A-Za-z0-9_%&',;=?$\x22]+$/.test(val) ? d(true) : d()
            }
            validateRule.message = '只能输入数字、字母，特殊字符'
          }
          if (ruleMap[1] === '08') {
            validateRule.validator = function(rule, val, d) {
              val && !/^[\u4E00-\u9FA5A-Za-z0-9_%&',;=?$\x22]+$/.test(val) ? d(true) : d()
            }
            validateRule.message = '只能输入数字、字母，特殊字符'
          }
        }
        validateArray.push(validateRule)
      })
      return validateArray
    }
  }
}
</script>

<style scoped>
  .app{
    padding: 30px 20% 30px 20%;
  }
  .el-input{
    width: 50px !important;
  }
</style>
